package com.bjpowernode.boss.web.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjpowernode.boss.constants.Constant;
import com.bjpowernode.boss.dao.domain.PmsOperator;
import com.bjpowernode.boss.dao.mapper.PmsOperatorMapper;
import com.bjpowernode.boss.exceptions.BossException;
import com.bjpowernode.boss.util.JwtUtil;
import com.bjpowernode.boss.util.RedisClient;
import com.bjpowernode.boss.web.model.dto.LoginResultDto;
import com.bjpowernode.boss.web.model.query.LoginQuery;
import com.bjpowernode.boss.web.service.AdminService;
import com.bjpowernode.enums.RespCode;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private PmsOperatorMapper pmsOperatorMapper;
    @Resource
    private  RedisClient redisClient;
    @Override
    public synchronized LoginResultDto login(LoginQuery loginQuery) {
        QueryWrapper<PmsOperator> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",loginQuery.getLoginName());
        PmsOperator pmsOperator = pmsOperatorMapper.selectOne(queryWrapper);
        if (pmsOperator == null) {
           throw new RuntimeException("登录用户不存在");
        }

//        获取盐值
            String salt = pmsOperator.getSalt();
//        根据前端返回的密码和盐值，通过MD5重新计算密码，并于数据库中的值作比较
        String newLoginPwd = DigestUtil.md5Hex(loginQuery.getLoginPwd() + salt);
        if (!newLoginPwd.equals(pmsOperator.getLoginPwd())){
//            throw new RuntimeException("用户名或密码错误,请重新输入");
            throw new BossException(RespCode.LOGIN_NAME_PWD_ERROR);
        }

//        生成token
        JSONObject json = new JSONObject();
        json.set("loginId", pmsOperator.getId());
        String jwt = JwtUtil.createJWT(json.toString(), 120);
//        储存token

        Map<String ,String>hashData = new HashMap<>();

        hashData.put("loginId",String.valueOf(pmsOperator.getId()));
        hashData.put("jwt",jwt);
        hashData.put("loginTime",new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        String AdminJwt = Constant.ADMIN_JWT + pmsOperator.getId();

        boolean flag = redisClient.addAllHash(AdminJwt,hashData,120, TimeUnit.MINUTES);

        if (!flag){
//            throw new RuntimeException("系统内部异常");
            throw new BossException(RespCode.LOGIN_INTERNVAL_ERROR);
        }
//        返回数据给前端
        return new LoginResultDto(pmsOperator.getId(),pmsOperator.getShowName(),jwt);
    }
}
